import re

from django import http
from django.contrib.auth import logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core import cache
from django.http import JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from kombu.utils import json

from apps.areas.models import Area, Address


class AreasView(View):

    def get(self,request):
        #提供省市区的数据
        area_id=request.GET.get('area_id')
        #读取缓存
        province_list = cache.cache.get('province_list')

        if not area_id:
            # 如果没有提供地区,则说明需要省信息
            #过滤父类parent id为空的
            try:
                province_model_list = Area.objects.filter(parent__isnull=True)
                #遍历列表,取出来的是列对象,然后在将需要返回的id和名字放到字典,
                #再将字典装入列表中返回
                province_list = []
                for province_model in province_model_list:
                    province_list.append({'id':province_model.id,'name':province_model.name})


            except Exception as e:
                print(e)
                return JsonResponse({'code': '-1', 'errmsg': '省份数据错误'})
            #写入缓存
            cache.cache.set('province_list', province_list, 3600)
            return JsonResponse({'code':'0', 'errmsg': 'OK', 'province_list': province_list})
        #如果存在area——id,则说明需要市和县
        else:
            try:
                # parent_model就是第一张表的,市级别
                parent_model = Area.objects.get(id=area_id)
                #取市级对应外键的所有
                sub_model_list = parent_model.subs.all() #取市级下面所有县级,即对应外键
                #将县级序列化
                sub_list = []
                for sub_model in sub_model_list:
                    sub_list.append({'id':sub_model.id,'name':sub_model.name})

                #父类表中的,关联自己,把市的id和name和县级的列表放到sub_data中
                sub_data ={'id':parent_model.id,
                           'name':parent_model.name,
                           'subs':sub_list}
            except Exception as e:
                print(e)
                return JsonResponse({'code': '-1', 'errmsg': '城市或区数据错误'})
            return JsonResponse({'code': '0', 'errmsg': 'OK', 'sub_data': sub_data})


#新增地址
class CreateAddressView(LoginRequiredMixin,View):

    def post(self,request):
        #先判断是否超过20个,已经超过20个则不会继续
        count = Address.objects.filter(user=request.user).count()

        if count >= 20:
            return http.JsonResponse({'code': '1', 'errmsg': '超过地址数量上限'})
        #如果不超过20个则开始准备添加,校验参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')
        # if not all([receiver, province_id, city_id, district_id, place, mobile]):
        #     return http.HttpResponseForbidden('缺少必传参数')
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseForbidden('参数mobile有误')
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.HttpResponseForbidden('参数tel有误')
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.HttpResponseForbidden('参数email有误')


        #校验成功后,保存信息
        try:
            #这里的address是一个对象了。
            address=Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
            #如果用户没有默认的地址则添加此地址为默认地址

            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception:
            return http.JsonResponse({'code': '-1', 'errmsg': '新增地址失败'})


        #新增地址成功,将进行局部刷新,返回保存成功后的值
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': '0', 'errmsg': '新增地址成功', 'address': address_dict})


#修改地址 删除地址
class UpdateAddressView(LoginRequiredMixin,View):

    def put(self,request,address_id):
        #还是接受参数
        json_dict=json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')


        #校验数据
        # if not all([receiver, province_id, city_id, district_id, place, mobile]):
        #     return http.HttpResponseForbidden('缺少必传参数')
        # if not re.match(r'^1[3-9]\d{9}$', mobile):
        #     return http.HttpResponseForbidden('参数mobile有误')
        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return http.HttpResponseForbidden('参数tel有误')
        # if email:
        #     if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
        #         return http.HttpResponseForbidden('参数email有误')


        #判断地址是否存在,存在更新信息
        try:
            # address_id是前端传过来需要修改的地址id
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception:
            return http.JsonResponse({'code': '-1', 'errmsg': '更新地址失败'})

        #成功之后要返回页面,刷新值
        #构造值
        address = Address.objects.get(id=address_id)
        address_dict ={
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return http.JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})


    def delete(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted=True
            address.save()
        except Exception:
            return http.JsonResponse({'code': '-1', 'errmsg': '删除地址失败'})
        return http.JsonResponse({'code': '0', 'errmsg': '删除地址成功'})


#设置默认地址
class DefaultAddressView(LoginRequiredMixin,View):
    def put(self,request,address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception:
            return http.JsonResponse({'code': '-1', 'errmsg': '设置默认地址失败'})
        return http.JsonResponse({'code': '0', 'errmsg': '设置默认地址成功'})

#修改标题
class UpdateTitleAddressView(View):
    def put(self,request,address_id):
        json_dict = json.loads(request.body.decode())
        title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title =title
            address.save()
        except Exception:
            return http.JsonResponse({'code': '-1', 'errmsg': '设置地址标题失败'})
        return http.JsonResponse({'code': '-1', 'errmsg': '设置地址标题成功'})

#修改密码
class ChangePasswordView(LoginRequiredMixin, View):
    def get(self,request):
        #展示修改密码页面
        return render(request, 'user_center_pass.html')

    def post(self,request):
        #提取参数
        old_password = request.POST.get('old_pwd')
        new_password = request.POST.get('new_pwd')
        new_password2 = request.POST.get('new_cpwd')
        #检验参数
        # if not all([old_password, new_password, new_password2]):
        #     return http.HttpResponseForbidden('缺少必传参数')
        # #检验密码
        # if not request.user.check_password(old_password):
        #     return render(request, 'user_center_pass.html', {'origin_pwd_errmsg':'原始密码错误'})
        # if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
        #     return http.HttpResponseForbidden('密码最少8位，最长20位')
        # if new_password != new_password2:
        #     return http.HttpResponseForbidden('两次输入的密码不一致')

        #密码正确开始修改密码
        #用django自带的修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
            print('修改到这里陈宫了')
        except Exception:
            return render(request, 'user_center_pass.html', {'change_pwd_errmsg': '修改密码失败'})


        #清理状态保持,清除session
        logout(request)
        #跳转到登录页面
        response = redirect(reverse('login'))
        response.delete_cookie('username')

        return response











